/*
 *MIT License
 *
 *Copyright (c) 2019 chenshuai cs4380@163.com
 *
 *Permission is hereby granted, free of charge, to any person obtaining a copy
 *of this software and associated documentation files (the "Software"), to deal
 *in the Software without restriction, including without limitation the rights
 *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *copies of the Software, and to permit persons to whom the Software is
 *furnished to do so, subject to the following conditions:
 *
 *The above copyright notice and this permission notice shall be included in all
 *copies or substantial portions of the Software.
 *
 *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *SOFTWARE.
 */

package com.cs.cslc.tool.oss.rest;

import com.cs.cslc.common.exception.BusinessException;
import com.cs.cslc.common.msg.ObjectResult;
import com.cs.cslc.tool.oss.cloud.CloudStorageService;
import com.cs.cslc.tool.oss.cloud.LocalStorageService;
import com.cs.cslc.tool.oss.cloud.OSSFactory;
import com.cs.cslc.tool.oss.config.CloudStorageConfig;
import com.cs.cslc.tool.oss.file.service.FilesServiceImpl;
import com.cs.cslc.tool.oss.util.FileUtil;
import com.cs.cslc.tool.oss.vo.FileVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * OssController 文件上传接口类.
 *
 * @author cs4380 https://gitee.com/xhbug_cs4380  cs4380@163.com
 * @version 1.0
 * @since 2024-07-15
 */
@Tag(name = "工具服务")
@RestController
@RequestMapping("/oss")
public class OssController {

    @Autowired
    private OSSFactory ossFactory;

    @Autowired
    private CloudStorageConfig cloudStorageConfig;

    @Autowired
    private FilesServiceImpl filesServiceImpl;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    @Operation(summary = "文件上传")
    public ObjectResult<FileVO> upload(@RequestParam("file") MultipartFile file) throws IOException {
        ObjectResult<FileVO> result = new ObjectResult<>();
        if (null == file || file.isEmpty()) {
            throw new BusinessException("上传文件不能为空！");
        }
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            throw new BusinessException("上传文件名不能为空！");
        }
        // 文件扩展名
        String suffix = filename.substring(filename.lastIndexOf("."));
        CloudStorageService storageService = ossFactory.build();
        FileVO fileVO = null;
        if (storageService instanceof LocalStorageService) {
            // 添加本地文件存储
            fileVO = LocalStorageService.saveLocalStorage(file, cloudStorageConfig.getLocalStoragePathPrefix());
        } else {
            String path = storageService.uploadSuffix(file.getBytes(), suffix);
            // 文件扩展名
            String fileName = filename.substring(0, filename.lastIndexOf("."));
            fileVO = FileVO.builder()
                    .sign(path)
                    .suffix(suffix)
                    .fileName(fileName)
                    .size(file.getSize())
                    .build();
        }
        if (null != fileVO) {
            filesServiceImpl.saveFile(fileVO);
        }
        result.setData(fileVO);
        return result;
    }

    /**
     * 文件上传
     */
    @PostMapping("/upload2")
    @Operation(summary = "文件上传")
    public ObjectResult<FileVO> upload2(@RequestParam("file") MultipartFile file) throws IOException {
        ObjectResult<FileVO> result = new ObjectResult<>();
        result.setData(FileVO.builder()
                .sign("https://qingruzhupublic.oss-cn-zhangjiakou.aliyuncs.com/20231004/016970130cb8452b9f0fdbf4aad2edc1.jpg")
                .suffix(".jpg")
                .fileName("test")
                .size(file.getSize())
                .build());
        return result;
    }
    /*
     *//**
     * 批量上传
     *//*
    @RequestMapping(value = "/uploads", method = {RequestMethod.GET, RequestMethod.POST})
    @Operation(summary = "批量上传")
    public ObjectResult<List<FileVO>> uploads(@RequestParam("files") MultipartFile[] files) throws IOException {
        if (files == null || files.length == 0) {
            throw new BusinessException("上传文件不能为空");
        }
        ObjectResult<List<FileVO>> result = new ObjectResult<>();
        //上传文件
        CloudStorageService storageService = ossFactory.build();
        List<FileVO> urls = new ArrayList<>();
        for (MultipartFile file : files) {
            String filename = file.getOriginalFilename();
            if (StringUtils.isBlank(filename)) {
                continue;
            }
            // 上传文件
            String suffix = filename.substring(filename.lastIndexOf("."));
            FileVO fileVO = null;
            if (storageService instanceof LocalStorageService) {
                // 添加本地文件存储
                fileVO = LocalStorageService.saveLocalStorage(file, cloudStorageConfig.getLocalStoragePathPrefix());
            } else {
                storageService.uploadSuffix(file.getBytes(), suffix);
            }
            urls.add(fileVO);
        }
        result.setData(urls);
        return result;
    }

    */

    /**
     * 文件下载
     *
     * @param path 文件路径（base64编码）
     */
    @RequestMapping(value = "/download/{path}", method = {RequestMethod.GET, RequestMethod.POST})
    @Operation(summary = "文件下载")
    public ResponseEntity<byte[]> download(@PathVariable("path") String path) throws IOException {
        if (StringUtils.isBlank(path)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        CloudStorageService storageService = ossFactory.build();
        if (storageService instanceof LocalStorageService) {
            //添加本地文件存储
            File file = FileUtil.getLocalStorageFile(cloudStorageConfig.getLocalStoragePathPrefix(), path);
            return FileUtil.download(file);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}
